package com.trs.controll;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.trs.dao.ConfigDao;
import com.trs.dao.DocDao;
import com.trs.dao.DocJsonDao;
import com.trs.dao.DocJsonTypeDao;
import com.trs.dao.ServerInfoDao;
import com.trs.entry.Config;
import com.trs.entry.DocJson;
import com.trs.entry.DocJsonType;
import com.trs.entry.ServerInfo;
import com.trs.util.DingDingUtil;
import com.trs.util.HttpClientUtil;
import com.trs.util.Results;
import com.trs.util.Txt;
import com.trs.util.Util;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.XML;
import lombok.extern.slf4j.Slf4j;

@RestController
@EnableScheduling
@Configuration
@Service
@Slf4j
public class Controller implements SchedulingConfigurer {

	@Resource
	DocDao docDao;

	@Resource
	ConfigDao configDao;

	@Resource
	DocJsonDao docJsonDao;

	@Resource
	DocJsonTypeDao docJsonTypeDao;

	@Resource
	ServerInfoDao serverInfoDao;

	@Value("${cron}")
	String cronString;

	@Value("${datapath}")
	String datapath;

	@Value("${hlwurl}")
	String hlwurl;

	@Value("${hlwurlpyq}")
	String hlwurlpyq;

	@Value("${hlwkey}")
	String hlwkey;

	@Value("${filesize}")
	Integer filesize;

	@Value("${datasave}")
	Integer datasave;

	static String fmt = "yyyyMMdd";
	static String fmt0 = "yyyy-MM-dd";
	static String fmt1 = "yyyy-MM-dd HH:mm:ss";
	static String fmt2 = "yyyyMMddHHmmss";

	@GetMapping(value = "/health")
	private String health(HttpServletRequest request) throws IOException {
		return "ok";
	}

	@Autowired
	private EntityManager entityManager;

	ConcurrentHashMap<Integer, Integer> push = new ConcurrentHashMap<>();

	@Override
	public void configureTasks(ScheduledTaskRegistrar task) {
		task.addCronTask(() -> {
			try {
				entityManager.clear(); // 清除缓存
				List<ServerInfo> list = serverInfoDao.findByType(1);
				for (ServerInfo serverInfo : list) {
					if (!push.containsKey(serverInfo.getId())) {
						executeService.execute(() -> {
							synchronized (serverInfo.getId()) {
								if (!Util.isNull(datapath) && !Util.isNull(serverInfo.getVirip())) {
									push.put(serverInfo.getId(), serverInfo.getId());
									log.info("定时扫描JSON文件: {} ", datapath + "/" + serverInfo.getVirip());
									traverseFiles(serverInfo, datapath + "/" + serverInfo.getVirip());
									push.remove(serverInfo.getId());
								}
							}
						});
					}
				}
			} catch (Exception e) {
				log.error("定时任务执行异常", e);
			}
		}, cronString);
	}
	//
	// @Scheduled(cron = "* * * * * ?")
	// private void taskReTry1() {
	// log.info("定时重置失败次数1");
	// }
	//
	// @Scheduled(cron = "* * * * * ?")
	// private void taskReTry2() {
	// log.info("定时重置失败次数21");
	// try {
	// Thread.sleep(3000);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// log.info("定时重置失败次数22");
	// }
	//
	// @Scheduled(cron = "* * * * * ?")
	// private void taskReTry3() {
	// log.info("定时重置失败次数3");
	// }

	@Scheduled(cron = "0 0 0 * * ?")
	private void taskReTry() {
		log.info("定时重置失败次数");
		docDao.updateRetry(-5, 0);
		docJsonDao.updateRetry(-5, 0);
	}

	// @Scheduled(cron = "0 0 0 * * ?")
	// private void taskReTrysend() {
	// log.info("定时重试接口推送");
	// List<DocJson> jsonlist = docJsonDao.findByRetryList();
	// for (DocJson json : jsonlist) {
	// sendHlw(json);
	// }
	// }

	// 定时更新微信登录状态、更新心跳监测
	@Scheduled(cron = "0/5 * * * * ?")
	private void taskXin() {
		for (Map.Entry<Integer, Long> entry : online.entrySet()) {
			if (entry.getValue() > 0 && new Date().getTime() > entry.getValue()) {
				entry.setValue(0L);
				serverInfoDao.updateStatusById(0, entry.getKey());
			}
		}
	}

	@SuppressWarnings("rawtypes")
	@GetMapping(value = "/pushstatus")
	public Results pushstatus() {
		List<ServerInfo> list = serverInfoDao.findByTypeAndChatoldNotAndChatoldNotNullOrderByArea(1, "");
		if (list.size() > 0) {
			for (ServerInfo serverInfo : list) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("workno", serverInfo.getChatold());// 机器号ID
				jsonObject.put("status", serverInfo.getStatus() == 1 ? 0 : 1);// 微信状态：0正常、1异常
				String resultString = "";
				try {
					log.info("华龙网推送: 微信状态: {} 原始参数: {}", serverInfo.getId(), jsonObject);
					SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, hlwkey.getBytes());
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("msgtype", "workstatus");
					param.put("msgcontent", aes.encryptHex(jsonObject.toJSONString()));
					resultString = HttpClientUtil.post(hlwurl, param);
					log.info("华龙网推送: 微信状态: {} 返回信息: {}", serverInfo.getId(), resultString);
					JSONObject rsobject = (JSONObject) JSONObject.parse(resultString);
					if (rsobject.containsKey("msg") && "操作成功".equals(rsobject.getString("msg"))) {
					} else {
						throw new Exception("请求异常");
					}
				} catch (Exception e) {
					log.error("华龙网推送: 微信状态: {} 异常消息返回体: {}", serverInfo.getId(), resultString, e);
					Results.error("操作异常: " + resultString + ": " + e.toString());
				}
			}
		}
		return Results.ok("操作成功");
	}

	@SuppressWarnings("rawtypes")
	@GetMapping(value = "/checkonline")
	public Results checkonline() {
		List<ServerInfo> listonline = serverInfoDao.findByTypeAndIssendDDAndStatusAndRealipNotAndRealipNotNullOrderByArea(1, 1, 1, "");
		List<ServerInfo> listonlinenot = serverInfoDao.findByTypeAndIssendDDAndStatusAndRealipNotAndRealipNotNullOrderByArea(1, 1, 0, "");
		StringBuilder string = new StringBuilder("线上网格已掉线数量: " + listonlinenot.size() + "   在线数量: " + listonline.size());
		if (listonlinenot.size() > 0) {
			// StringJoiner joinstring = new StringJoiner(" > ");
			for (ServerInfo serverInfo : listonlinenot) {
				// System.out.println(StringUtils.join(serverInfo.getRealip(), " : ", serverInfo.getArea(), " > ", serverInfo.getStree(), " > ", serverInfo.getPeople(), " : ", serverInfo.getPhone()));
				string.append("\n" + serverInfo.getRealip() + " : " + serverInfo.getArea() + " > " + serverInfo.getStree() + " > " + serverInfo.getPeople() + " : " + serverInfo.getPhone());
			}
			try {
				DingDingUtil.sendText(string.toString(), false, Arrays.asList(people.getValue().split(",")));
			} catch (Exception e) {
				log.error("钉钉消息发送异常", e);
			}
			return Results.ok(string);
		} else {
			return Results.ok("暂无掉线");
		}
	}

	@GetMapping(value = "/deletefile")
	public void deletefile(String filepath, Integer type) {
		log.info("主动清理文件: {} {}", datapath, filepath);
		List<ServerInfo> list = serverInfoDao.findByType(1);
		ExecutorService executeServicedele = Executors.newFixedThreadPool(64);
		for (ServerInfo serverInfo : list) {
			executeServicedele.execute(() -> {
				synchronized (serverInfo.getId()) {
					if (!Util.isNull(datapath) && !Util.isNull(serverInfo.getVirip())) {
						deleteFile(new File(datapath + "/" + serverInfo.getVirip() + filepath), type);
					}
				}
			});
		}
		executeServicedele.shutdown();
	}

	@Scheduled(cron = "0 0 1 * * ?")
	public void deletedata() {
		deletedata(null);
	}

	@GetMapping(value = "/deletedata")
	public Results<?> deletedata(String date) {
		Calendar calendar = Calendar.getInstance();
		if (Util.isNull(date)) {
			if (Util.isNull(datasave)) {
				datasave = 30;
			}
			calendar.add(Calendar.DATE, -datasave);
			date = DateFormatUtils.format(calendar.getTime(), fmt0);
		}
		String dateString = date;
		try {
			log.info("删除JSON数据: {}", date);
			Integer maxid = docJsonDao.findByDate(DateUtils.parseDate(dateString, fmt0));
			List<String> dataList = docJsonDao.findDate(DateUtils.parseDate(dateString, fmt0));
			List<ServerInfo> list = serverInfoDao.findAll();
			ExecutorService es = Executors.newFixedThreadPool(12);
			for (ServerInfo serverInfo : list) {
				if (!Util.isNull(serverInfo.getVirip())) {
					es.execute(() -> {
						synchronized (serverInfo.getId()) {
							log.info("删除JSON数据文件: serverid : {} maxid: {}", serverInfo.getId(), maxid);
							for (String string : dataList) {
								deleteFile(new File(datapath + "/" + serverInfo.getVirip() + "/message/ok/" + string.replace("-", "")), 0);
								deleteFile(new File(datapath + "/" + serverInfo.getVirip() + "/chatroom/ok/" + string.replace("-", "")), 0);
								deleteFile(new File(datapath + "/" + serverInfo.getVirip() + "/chatroom/ok/@wwj@chatroom_info_" + string.replace("-", "")), 0);
							}
						}
					});
				}
			}
			es.shutdown();
			while (!es.isTerminated()) {// 查看线程是否完成关闭
				try {
					es.awaitTermination(5, TimeUnit.SECONDS);
				} catch (InterruptedException e) {
					log.error("删除JSON数据异常", e);
				}
			}
			log.info("删除JSON数据文件完成: {}", date);
			docJsonDao.deleteByIdless(maxid);
			log.info("删除JSON数据完成: {}", date);
		} catch (Exception e) {
		}

		return Results.ok(date);
	}

	@GetMapping(value = "/deletedata1")
	public Results<?> deletedata1(String date) {
		if (datasave == null) {
			datasave = 30;
		}
		Date date0 = new Date();
		Calendar calendar = Calendar.getInstance();
		if (StringUtils.isBlank(date)) {
			calendar.add(Calendar.DATE, -datasave);
			date0 = calendar.getTime();
		} else {
			try {
				date0 = DateUtils.parseDate(date, fmt0);
			} catch (ParseException e) {
				calendar.add(Calendar.DATE, -datasave);
				date0 = calendar.getTime();
			}
		}
		Date datefinalDate = date0;
		try {
			log.info("删除文件数据: {}", DateFormatUtils.format(datefinalDate, fmt0));
			ExecutorService es = Executors.newFixedThreadPool(12);
			File file = new File(datapath);
			if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (File newfile : files) {// 遍历文件夹下的目录
					es.execute(() -> {
						synchronized (newfile.getPath()) {
							log.info("删除文件数据: {} ", DateFormatUtils.format(datefinalDate, fmt0));
							deleteFile(newfile, datefinalDate);
						}
					});
				}
			}
			es.shutdown();
			while (!es.isTerminated()) {// 查看线程是否完成关闭
				try {
					es.awaitTermination(5, TimeUnit.SECONDS);
				} catch (InterruptedException e) {
					log.error("删除文件数据异常", e);
				}
			}
			log.info("删除文件数据完成: {}", DateFormatUtils.format(datefinalDate, fmt0));
			Integer maxid = docJsonDao.findByDate(datefinalDate);
			log.info("删除JSON数据:  maxid: {}", maxid);
			if (maxid != null) {
				docJsonDao.deleteByIdless(maxid);
			}
			log.info("删除JSON数据完成: {}", DateFormatUtils.format(datefinalDate, fmt0));
		} catch (Exception e) {
		}

		return Results.ok(DateFormatUtils.format(datefinalDate, fmt0));
	}

	@Value("${ddsecret}")
	String ddsecret;
	@Value("${ddurl}")
	String ddurl;
	@Value("${executeService}")
	private Integer executeServicenum;
	public ExecutorService executeService = null;
	Config people;
	HashMap<Integer, DocJsonType> typemap = new HashMap<>();
	HashMap<Integer, Long> online = new HashMap<>();

	@PostConstruct
	public void initThreadPool() {
		DingDingUtil.SECRET = ddsecret;
		DingDingUtil.URL = ddurl;
		executeService = Executors.newFixedThreadPool(executeServicenum);
		people = configDao.findByName("people");
		List<DocJsonType> list = docJsonTypeDao.findAll();
		for (DocJsonType docJsonType : list) {
			typemap.put(docJsonType.getApi(), docJsonType);
		}

		List<ServerInfo> serverlist = serverInfoDao.findByType(1);
		for (ServerInfo server : serverlist) {
			if (server.getStatus() == 1) {
				online.put(server.getId(), new Date().getTime() + 5 * 60 * 1000);
			} else {
				online.put(server.getId(), 0L);
			}
		}
	}

	public void traverseFiles(ServerInfo serverInfo, String filepath) {
		File folder = new File(filepath);
		if (folder.isDirectory()) {
			File[] files = folder.listFiles();
			if (files != null) {
				for (File file : files) {
					if (file.isDirectory()) {
						if (file.getPath().indexOf("ok") < 0) {
							traverseFiles(serverInfo, file.getPath()); // 递归调用，遍历子文件夹中的文件
						}
					} else {
						if (file.getName().endsWith(".json.gz")) {
							try {
								if (file.exists()) {

									// 推送完成目录创建
									File toFiles = null;
									toFiles = new File(filepath + "/ok/" + DateFormatUtils.format(new Date(), fmt));
									if (!toFiles.exists()) {
										toFiles.mkdirs();
									}

									// 3.9.10脏数据
									if ("_info.json.gz".equals(file.getName())) {
										deleteFile(file, 0);
										continue;
									}
									String jsonString = Txt.readGzFile(file.getPath());
									if (!Util.isNull(jsonString)) {
										JSONArray jsonArray = new JSONArray();
										if (jsonString.startsWith("[")) {
											jsonArray = JSONArray.parseArray(jsonString);
										} else {
											JSONObject jsonObject = JSONObject.parseObject(jsonString);
											jsonArray.add(jsonObject);
										}

										boolean delete = true;
										for (int i = 0; i < jsonArray.size(); i++) {
											JSONObject jsonObject = jsonArray.getJSONObject(i);
											if (!typemap.containsKey(jsonObject.getInteger("api")) || typemap.get(jsonObject.getInteger("api")).getIsdelete() == 0) {
												delete = false;
											}
										}

										File toFile = null;
										if (delete) {
											deleteFile(file, 0);
										} else {
											if (file.exists()) {
												if (file.getName().indexOf("@chatroom_info.json.gz") > -1) {
													toFile = new File(toFiles.getPath() + "/" + file.getName().replace("@chatroom_info", "@chatroom_info_" + DateFormatUtils.format(new Date(), fmt2)));
												} else {
													toFile = new File(toFiles.getPath() + "/" + file.getName());
												}
												boolean isMoved = file.renameTo(toFile);
												if (isMoved) {
													// log.info("文件成功移动到新位置: 原始文件: {} 目标文件: {}", file.getPath(), toFile.getPath());
												} else {
													log.error("无法移动文件: 原始文件: {} 目标文件: {}", file.getPath(), toFile.getPath());
												}
											} else {
												log.info("源文件不存在");
											}
										}
										for (int i = 0; i < jsonArray.size(); i++) {
											JSONObject jsonObject = jsonArray.getJSONObject(i);
											DocJson json = new DocJson(serverInfo.getId(), file.getName(), jsonObject.toJSONString());
											json.setFullpath(toFile != null ? toFile.getPath() : file.getPath());
											if (typemap.containsKey(jsonObject.getInteger("api"))) {
												json.setType(typemap.get(jsonObject.getInteger("api")).getApi());
												json.setIssend(typemap.get(jsonObject.getInteger("api")).getIssend());

												if (json.getType() == 1005 || json.getType() == 1050) {
													String filestring = jsonObject.getJSONObject("data").getJSONObject("bytesExtra").getString("thumb_raw");
													if (!Util.isNull(filestring)) {
														filestring = datapath + "/" + serverInfo.getVirip() + "/message/files/" + DigestUtils.md5Hex(filestring).toUpperCase() + filestring.substring(filestring.lastIndexOf("."));
														deleteFile(new File(filestring), 0);
													}
													filestring = jsonObject.getJSONObject("data").getJSONObject("bytesExtra").getString("image_raw");
													if (!Util.isNull(filestring)) {
														filestring = datapath + "/" + serverInfo.getVirip() + "/message/files/" + DigestUtils.md5Hex(filestring).toUpperCase() + filestring.substring(filestring.lastIndexOf("."));
													} else {
														filestring = jsonObject.getJSONObject("data").getJSONObject("bytesExtra").getString("file_raw");
														if (!Util.isNull(filestring)) {
															filestring = datapath + "/" + serverInfo.getVirip() + "/message/files/" + DigestUtils.md5Hex(filestring).toUpperCase() + filestring.substring(filestring.lastIndexOf("."));
														}
													}
													json.setFilepath(filestring);

													if (json.getType() == 1050 && "语音".equals(jsonObject.getJSONObject("data").getString("typeInfo"))) {
														json.setFilepath(datapath + "/" + serverInfo.getVirip() + "/message/files/" + jsonObject.getJSONObject("data").getString("msgSvrID") + ".mp3");
													}
												}

												// 获取微信用户名
												if (json.getType() == 1002) {
													serverInfo.setChat(jsonObject.getJSONObject("data").getString("alias"));
													serverInfo.setChatname(jsonObject.getJSONObject("data").getString("nickName"));
													serverInfo = serverInfoDao.save(serverInfo);
												}

												// 监控微信登录状态
												if (!online.containsKey(serverInfo.getId())) {
													online.put(serverInfo.getId(), 0L);
												}
												if (json.getType() == 1111 && jsonObject.getJSONObject("data").getInteger("isLogin") == 1) {
													if (serverInfo.getStatus() == 0 || online.get(serverInfo.getId()) == 0) {
														serverInfo.setStatus(1);
														serverInfo.setChatnew(jsonObject.getString("wechat"));
														serverInfo.setStatusTime(new Date());
														serverInfo = serverInfoDao.save(serverInfo);
													}
													online.put(serverInfo.getId(), new Date().getTime() + 5 * 60 * 1000);
												}
												if (json.getType() == 1003 && "微信退出".equals(jsonObject.getString("msg"))) {
													if (serverInfo.getStatus() == 1 || online.get(serverInfo.getId()) > 0) {
														serverInfo.setStatus(0);
														serverInfo.setStatusTime(new Date());
														serverInfoDao.save(serverInfo);
													}
													online.put(serverInfo.getId(), 0L);
												}

												if (typemap.get(jsonObject.getInteger("api")).getIssave() == 1) {
													try {
														json = docJsonDao.save(json);
														// log.info("JSON文件: {}", json);
													} catch (Exception e) {
														log.error("JSON保存异常: {}", json, e);
													}
												}

												// 推送消息
												if (json.getType() == 1005 || json.getType() == 1050 || json.getType() == 2111 || json.getType() == 2804) {
													sendHlw(json);
												}
											} else {
												json = docJsonDao.save(json);
												log.info("JSON文件未知类型: {}", json);
											}
										}
									}
								}
							} catch (Exception e) {
								log.error("JSON文件操作异常: {}", file.getPath(), e);
							}
						}
					}
				}
			}
		}

	}

	public void sendHlw(DocJson messagejson) {
		try {
			JSONObject info;
			if (messagejson.getContent().startsWith("[")) {
				JSONArray ar = JSONArray.parseArray(messagejson.getContent());
				if (ar.size() == 1) {
					info = ar.getJSONObject(0);
				} else if (ar.size() == 2) {
					info = ar.getJSONObject(1);
				} else {
					info = ar.getJSONObject(2);
				}
			} else {
				info = JSONObject.parseObject(messagejson.getContent());
			}
			String workno = info.getString("wechat");
			if (Util.isNull(workno)) {
				docJsonDao.updateIsSend(2, messagejson.getId());
			} else {
				if (messagejson.getType() == 1005 || messagejson.getType() == 1050) {
					info = info.getJSONObject("data");
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("workno", workno);// 机器号ID
					jsonObject.put("groupno", info.getString("userName"));// 群ID
					jsonObject.put("groupname", info.getString("nickName"));// 群名称
					jsonObject.put("wxno", info.getJSONObject("bytesExtra").getString("userName"));// 微信号ID
					jsonObject.put("wxname", info.getJSONObject("bytesExtra").getString("nickName"));// 微信昵称
					jsonObject.put("msgorder", info.getString("sortIndex"));// 消息顺序
					jsonObject.put("msgtime", DateFormatUtils.format(Long.parseLong(info.getString("createTime") + "000"), fmt1));// 消息时间
					jsonObject.put("smallheadimgurl", info.getJSONObject("bytesExtra").getString("smallHeadImgUrl"));// 头像
					jsonObject.put("bigheadimgurl", info.getJSONObject("bytesExtra").getString("bigHeadImgUrl"));// 头像

					switch (info.getString("typeInfo")) {// 消息类型：1文本、2链接、3图片、4视频、5其他、6语音转文字
					case "文字":
						jsonObject.put("msgtype", 1);
						jsonObject.put("msgtxt", info.getString("strContent"));// 消息内容
						break;
					case "XML消息(链接)":
						jsonObject.put("msgtype", 2);
						info = JSONObject.parseObject(XML.toJSONObject(info.getString("strContent")).getJSONObject("msg").toString());
						jsonObject.put("urltitle", info.getJSONObject("appmsg").getString("title"));
						jsonObject.put("urldes", info.getJSONObject("appmsg").getString("des"));
						jsonObject.put("urladdr", info.getJSONObject("appmsg").getString("url"));
						try {
							jsonObject.put("urlappname", info.getJSONObject("appinfo").getString("appname"));
						} catch (Exception e) {
							jsonObject.put("urlappname", "未知");
						}
						break;
					case "图片":
						jsonObject.put("msgtype", 3);
						if (Util.isNull(messagejson.getFilepath())) {
							docJsonDao.updateIsSend(3, messagejson.getId());
							return;
						}
						break;
					case "视频":
						jsonObject.put("msgtype", 4);
						if (Util.isNull(messagejson.getFilepath())) {
							docJsonDao.updateIsSend(3, messagejson.getId());
							return;
						}
						break;
					case "XML消息(文件)":
						jsonObject.put("msgtype", 5);
						if (Util.isNull(messagejson.getFilepath())) {
							docJsonDao.updateIsSend(3, messagejson.getId());
							return;
						}
						break;
					case "语音":
						jsonObject.put("msgtype", 6);
						if (Util.isNull(messagejson.getFilepath())) {
							docJsonDao.updateIsSend(3, messagejson.getId());
							return;
						}
						break;
					default:
						docJsonDao.updateIsSend(2, messagejson.getId());
						return;
					}
					send(messagejson, jsonObject, "message", messagejson.getFilepath());
				}

				if (messagejson.getType() == 2111) {
					JSONArray users = new JSONArray();
					JSONArray userstring = info.getJSONObject("data").getJSONArray("member");
					for (int i = 0; i < userstring.size(); i++) {
						JSONObject user = new JSONObject();
						user.put("wxno", userstring.getJSONObject(i).getString("userName"));
						user.put("wxname", userstring.getJSONObject(i).getString("nickName"));
						user.put("smallheadimgurl", userstring.getJSONObject(i).getString("smallHeadImgUrl"));
						user.put("bigheadimgurl", userstring.getJSONObject(i).getString("bigHeadImgUrl"));
						users.add(user);
					}
					JSONObject group = new JSONObject();
					group.put("groupno", info.getJSONObject("data").getString("chatRoomName"));
					group.put("groupname", info.getJSONObject("data").getString("nickName"));
					group.put("members", users);
					JSONArray groups = new JSONArray();
					groups.add(group);

					JSONObject jsonObject = new JSONObject();
					jsonObject.put("workno", workno);// 机器号ID
					jsonObject.put("groups", groups);// 群ID

					send(messagejson, jsonObject, "member", null);
				}

				if (messagejson.getType() == 2804) {
					sendpyq(messagejson, info, "1", messagejson.getFilepath());// msgType 消息类型 1.文本 2.链接 3图片 4.视频 5.文件，默认1
				}
			}
		} catch (Exception e) {
			log.error("华龙网推送: 消息ID: {} 消息内容: {}", messagejson.getId(), messagejson, e);
		}
	}

	public void deleteFile(File file, Integer type) {
		try {
			if (file.getPath().indexOf("@wwj@") > -1) {
				File file1 = file.getParentFile();
				if (file1.isDirectory()) {
					File files[] = file1.listFiles();
					for (File newfile : files) {// 遍历文件夹下的目录
						if (newfile.getName().indexOf(file.getName().replace("@wwj@", "")) > -1) {
							if (newfile.isFile()) {
								log.info("删除JSON文件: {} ", newfile.getPath());
								newfile.delete();
							}

							if (type != null && type == 1) {
								log.info("删除JSON文件夹: {} ", newfile.getPath());
								deleteFile(newfile, type);// 是文件夹,递归调用方法
							}
						}
					}
				}
				return;
			}

			if (file.exists()) {// 判断文件是否存在
				if (file.isDirectory()) {
					File files[] = file.listFiles();
					for (File newfile : files) {// 遍历文件夹下的目录
						if (newfile.isFile()) {// 如果是文件而不是文件夹==>可直接删除
							boolean deleted = newfile.delete();
							if (deleted) {
								log.info("删除JSON文件成功: {} ", newfile.getPath());
							} else {
								log.info("无法删除JSON文件: {} ", file.getPath());
							}
						} else {
							deleteFile(newfile, type);// 是文件夹,递归调用方法
						}
					}
					log.info("删除JSON文件夹: {} ", file.getPath());
					file.delete();
				} else {
					log.info("删除JSON文件: {} ", file.getPath());
					file.delete();
				}
			}
		} catch (Exception e) {
			log.error("{}", e);
		}
	}

	public void deleteFile(File file, Date cutoffDate) {
		try {
			if (file.exists()) {// 判断文件是否存在
				if (file.isDirectory()) {
					File files[] = file.listFiles();
					for (File newfile : files) {// 遍历文件夹下的目录
						Path path = Paths.get(newfile.getAbsolutePath());
						BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
						Date lastModified = new Date(attrs.lastModifiedTime().toMillis());
						if (cutoffDate == null || lastModified.before(cutoffDate) || newfile.getPath().endsWith("chatroom") || newfile.getPath().endsWith("message") || newfile.getPath().endsWith("ok") || newfile.getPath().endsWith("files")) {// 比较文件修改时间和截止时间
							if (newfile.isFile()) {// 如果是文件而不是文件夹==>可直接删除
								// 如果文件在截止时间之前修改，则删除
								boolean deleted = newfile.delete();
								if (deleted) {
									log.info("删除JSON文件成功: {} ", newfile.getPath());
								} else {
									log.info("无法删除JSON文件: {} ", newfile.getPath());
								}
							} else {
								deleteFile(newfile, cutoffDate);// 是文件夹,递归调用方法
							}
						}
					}

					// 删除内部文件后删除自身
					log.info("删除JSON文件夹: {} ", file.getPath());
					file.delete();
				} else {
					// 判断第一次调用是文件，说明需要直接删除
					log.info("删除JSON文件: {} ", file.getPath());
					file.delete();
				}
			}
		} catch (Exception e) {
			log.error("{}", e);
		}
	}

	public void send(DocJson json, JSONObject jsonObject, String type, String file) {
		try {
			// log.info("华龙网推送: 消息ID: {} 原始参数: {}", json.getId(), jsonObject);
			SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, hlwkey.getBytes());
			// Map<String, Object> param = new HashMap<String, Object>();
			// param.put("msgtype", type);
			// param.put("msgcontent", aes.encryptHex(jsonObject.toJSONString()));

			Map<String, ContentBody> content = new HashMap<String, ContentBody>();
			ContentType create = ContentType.create("multipart/form-data", Charset.forName("UTF-8"));
			content.put("msgtype", new StringBody(type, create));
			content.put("msgcontent", new StringBody(aes.encryptHex(jsonObject.toJSONString()), create));

			if (!Util.isNull(file)) {
				File files = new File(file);
				if (files.exists()) {
					if (files.length() < filesize * 1000 * 1000) {
						// log.info("华龙网推送: 消息ID: {} 文件信息: {}", json.getId(), file);
						content.put("file", new FileBody(new File(file)));
					} else {
						log.info("华龙网推送: 消息ID: {}  {} 文件大小超过限制", json.getId(), file);
					}
				} else {
					log.info("华龙网推送: 消息ID: {}  {} 文件不存在", json.getId(), file);
					docJsonDao.updateIsSend(4, json.getId());
					return;
				}
			}
			String resultString = HttpClientUtil.post1(hlwurl, null, content);
			// log.info("华龙网推送: 消息ID: {} 返回信息: {}", json.getId(), resultString);
			JSONObject rsobject = (JSONObject) JSONObject.parse(resultString);
			if (rsobject.containsKey("msg") && "操作成功".equals(rsobject.getString("msg"))) {
				docJsonDao.updateIsSend(1, json.getId());
				if (!Util.isNull(file)) {
					deleteFile(new File(file), 0);
					deleteFile(new File(file.replace(".mp3", ".silk")), 0);
				}
			} else if ("{\"msg\":\"文件上传错误\",\"code\":500}".equals(resultString)) {
				log.info("华龙网推送: 消息ID: {} {} {} ", resultString, json.getId(), file);
				docJsonDao.updateIsSend(5, json.getId());
				return;
			} else {
				throw new Exception("请求异常: " + resultString);
			}
		} catch (Exception e) {
			docJsonDao.updateIsSend(json.getIssend() + 1, json.getId());
			log.error("华龙网推送: 消息ID: {} 异常信息: {} 请求参数: {}", json.getId(), e.getMessage(), jsonObject, e);
		}
	}

	public void sendpyq(DocJson json, JSONObject jsonObject, String type, String file) {
		try {
			// log.info("华龙网推送: 消息ID: {} 原始参数: {}", json.getId(), jsonObject);
			Map<String, ContentBody> content = new HashMap<String, ContentBody>();
			ContentType create = ContentType.create("multipart/form-data", Charset.forName("UTF-8"));
			content.put("msgType", new StringBody(type, create));
			content.put("pram", new StringBody(jsonObject.toJSONString(), create));

			if (!Util.isNull(file)) {
				File files = new File(file);
				if (files.exists()) {
					if (files.length() < filesize * 1000 * 1000) {
						// log.info("华龙网推送: 消息ID: {} 文件信息: {}", json.getId(), file);
						content.put("file", new FileBody(new File(file)));
					} else {
						log.info("华龙网朋友圈推送: 消息ID: {}  {} 文件大小超过限制", json.getId(), file);
					}
				} else {
					log.info("华龙网朋友圈推送: 消息ID: {}  {} 文件不存在", json.getId(), file);
					docJsonDao.updateIsSend(4, json.getId());
					return;
				}
			}
			String resultString = HttpClientUtil.post1(hlwurlpyq, null, content);
			// log.info("华龙网推送: 消息ID: {} 返回信息: {}", json.getId(), resultString);
			JSONObject rsobject = (JSONObject) JSONObject.parse(resultString);
			if (rsobject.containsKey("msg") && "success".equals(rsobject.getString("msg"))) {
				docJsonDao.updateIsSend(1, json.getId());
				if (!Util.isNull(file)) {
					deleteFile(new File(file), 0);
					deleteFile(new File(file.replace(".mp3", ".silk")), 0);
				}
			} else {
				throw new Exception("请求异常: " + resultString);
			}
		} catch (Exception e) {
			docJsonDao.updateIsSend(json.getIssend() + 1, json.getId());
			log.error("华龙网朋友圈推送: 消息ID: {} 异常信息: {} 请求参数: {}", json.getId(), e.getMessage(), jsonObject, e);
		}
	}

	// public boolean getJsonString1(String filename, String filePath) {
	// if (filePath.endsWith(".json")) {
	// if (docJsonDao.findByPathAndServerid(filename, 0) == null) {
	// try {
	// String jsonString = Txt.read1(filePath);
	// if (!Util.isNull(jsonString)) {
	// DocJson json = new DocJson(filename, filename, jsonString);
	// json = docJsonDao.save(json);
	// log.info("JSON文件: ", json);
	// Doc doc = dealJson(json.getContent());
	// if (doc != null) {
	// docJsonDao.updateDocid(doc.getId(), json.getId());
	// sendHlw(doc);
	// return true;
	// }
	// } else {
	// log.info("JSON文件内容为空: {} ", filePath);
	// }
	// } catch (Exception e) {
	// log.error("JSON文件操作异常: {}", filePath, e);
	// }
	// }
	// }
	// return false;
	// }

	public static void main(String[] args) {
		File file = new File("/data/share/113.250.189.19_2080/chatroom/ok/_info.js/_info.json.gz");
		System.out.println("_info.json.gz".equals(file.getName()));

		try {
			Date date = DateUtils.parseDate("2024-06-06 07:24:05", new String[] { "yyyy-MM-dd HH:mm:ss" });
			System.err.println(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		String long2Str = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
		String date2Str = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		System.err.println(long2Str + date2Str);

		System.err.println(DateFormatUtils.format(Long.parseLong("1717629845000"), "yyyy-MM-dd HH:mm:ss"));

		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		// LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong("1717629845000")), ZoneId.systemDefault());
		System.err.println(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong("1717629845000")), ZoneId.systemDefault()).format(formatter));

		System.err.println(LocalDateTime.now().format(formatter));

		LocalDateTime.now();

		System.err.println(new Date().getTime());
		// System.err.println(fmt1.format(new Date().getTime()));
		// System.err.println(fmt1.format(new Date().getTime() + 10000));
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -10);
		System.err.println(DateFormatUtils.format(calendar.getTime(), fmt0));

		System.err.println(DigestUtils.md5Hex("C:\\Users\\test\\AppData\\Local\\wxapi\\wxid_mlp8ykpzx9g922\\Image\\Thumb\\2024-05\\12ca7d020a47b948c0800ed7e2eb2e41_t.jpg").toUpperCase());
	}
}
